package pres.sweven.tabpager.helper

import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout

/**
 * Created by Sweven on 2022/6/22.
 * Email:sweventears@Foxmail.com
 */
class TabHelper(
    val tabLayout: TabLayout,
    val viewPager: ViewPager,
    val onCustomViewChange: CustomViewChange? = null
) : TabLayout.OnTabSelectedListener, ViewPager.OnPageChangeListener {

    init {
        tabLayout.addOnTabSelectedListener(this)
        viewPager.addOnPageChangeListener(this)
    }

    fun <T> addPagerData(adapter: FragmentPagerAdapter,list: List<T>) {
        for (i in 0..adapter.count) {
            val pageTitle = adapter.getPageTitle(i)
            val newTab = tabLayout.newTab()
            newTab.text = pageTitle
            newTab.tag = pageTitle
            newTab.customView = onCustomViewChange?.addCustomView(list[i])
            tabLayout.addTab(newTab)
        }
    }

    override fun onTabSelected(tab: TabLayout.Tab?) {
        viewPager.currentItem = tab?.position ?: 0
        onCustomViewChange?.onSelected(tab?.customView)
    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {
        onCustomViewChange?.unSelected(tab?.customView)
    }

    override fun onTabReselected(tab: TabLayout.Tab?) {
    }

    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
    }

    override fun onPageSelected(position: Int) {
        tabLayout.getTabAt(position)?.select()
    }

    override fun onPageScrollStateChanged(state: Int) {
    }
}